package com.e3.basdoc.dept.dao;

import java.util.List;

import com.e3.basdoc.dept.entity.DeptEntity;
import com.e3.basdoc.dept.model.DeptModel;
import com.e3.basdoc.dept.model.DeptQC;
import com.e3.core.base.SuperDAO;

public class DeptDAO extends SuperDAO {

	private String querySQL = "SELECT t FROM DeptEntity t";

	public List<DeptEntity> getDeptsByCondition(DeptQC DeptQC) {
		String sql = querySQL;
		DeptQC.setPrefix("t");
		String whereSQL = DeptQC.getWhereSQL();
		if (whereSQL != null && whereSQL.length() > 0) {
			sql = sql + " WHERE " + whereSQL;
		}
		return this.find(sql);
	}

	public void deleteDeptByCodes(List<DeptModel> deptModels) {
		if (deptModels == null || deptModels.isEmpty()) {
			return;
		}
		String[] codes = new String[deptModels.size()];
		for (int i = 0; i < deptModels.size(); i++) {
			codes[i] = deptModels.get(i).getCode();
		}
		this.deleteAllBySingleField(DeptEntity.class, "code", codes);
	}

	public void deleteDeptByIds(Long[] ids) {
		this.deleteAllBySingleField(DeptEntity.class, "id", ids);
	}

	public void deleteDeptChildren(Long[] parentIds) {
		if (parentIds == null || parentIds.length == 0) {
			return;
		}
		this.deleteAllBySingleField(DeptEntity.class, "parentId", parentIds);
	}

	public DeptEntity getDeptByCode(String code) {
		String whSql = " WHERE t.code = ?";
		String sql = querySQL + whSql;
		List<DeptEntity> entities = this.find(sql, code);
		return (entities == null || entities.size() == 0) ? null : entities.get(0);
	}

	public DeptEntity getCorpDeptByCode(String code, long corpId) {
		String whSql = " WHERE t.code =:code and t.corpId =:corpId";
		String sql = querySQL + whSql;
		List<DeptEntity> entities = this.findByNamedParams(sql, new String[] { "code", "corpId" }, new Object[] { code, corpId });
		return (entities == null || entities.size() == 0) ? null : entities.get(0);
	}

	public long childrenCount(long pId) {
		String sql = "SELECT count(t) FROM DeptEntity t WHERE t.parentId = ?";
		return this.counter(sql, pId);
	}

	public long childrenCount(long parentId, long corpId) {
		String whSql = " WHERE t.parentId =:parentId and t.corpId =:corpId";
		String sql = querySQL + whSql;
		List<DeptEntity> entities = this.findByNamedParams(sql, new String[] { "parentId", "corpId" }, new Object[] { parentId, corpId });
		return (entities == null) ? 0 : entities.size();
	}

	public List<DeptEntity> getChildren(long parentId, long corpId) {
		String whSql = " WHERE t.parentId =:parentId and t.corpId =:corpId";
		String sql = querySQL + whSql;
		List<DeptEntity> entities = this.findByNamedParams(sql, new String[] { "parentId", "corpId" }, new Object[] { parentId, corpId });
		return entities;
	}

}
